import yfinance as yf
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from sklearn.preprocessing import MinMaxScaler

# 1. 获取股票数据
data = yf.download('AAPL', start='2010-01-01', end='2023-12-31')
prices = data['Close'].values.reshape(-1, 1)

# 2. 归一化与滑动窗口构造
scaler = MinMaxScaler()
scaled_prices = scaler.fit_transform(prices)
X, y = create_dataset(scaled_prices, T=60)  # 过去60天预测次日

# 3. 构建LSTM模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(60, 1)))
model.add(Dropout(0.2))
model.add(LSTM(50))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')

# 4. 训练与预测
model.fit(X, y, epochs=100, batch_size=32, validation_split=0.1)
pred = model.predict(X[-1].reshape(1, 60, 1))  # 预测下一个交易日
pred_price = scaler.inverse_transform(pred)